﻿
using SqlSugar;
using System.Runtime.CompilerServices;
using Zhao.Models.Entity;
using Zhao.Repository.Base;

namespace Zhao.Arena.Utility.InitDatabaseExt
{
    /// <summary>
    /// 初始化SqlSugar
    /// </summary>
    public static class InitSqlSugarExt
    {
        /// <summary>
        /// 初始化SqlSugar
        /// </summary>
        public static void InitSqlSugar(this WebApplicationBuilder builder)
        {
            //读取配置文件中的数据库连接字符串
            string? connectionString = builder.Configuration.GetConnectionString("ConnectionString");
            //判断连接字符串是否为空  如为空直接抛异常
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new Exception("请配置数据库连接字符串");
            }

            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConnectionString = connectionString,
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            };

            builder.Services.AddScoped<ISqlSugarClient>(x =>
            {
                SqlSugarClient client = new SqlSugarClient(connectionConfig);

                #region SqlSugarAop
                //在执行SQL操作的时候 可以进行的一些操作的相关配置
                client.Aop.OnLogExecuting = (s, p) =>
                {
                    Console.WriteLine($"OnLogExecuting:输出Sql语句;{s} || 参数为{string.Join(",", p.Select(x => x.Value))}");
                };
                client.Aop.OnLogExecuted = (s, p) =>
                {
                    Console.WriteLine($"OnLogExecuted:输出Sql语句;{s} || 参数为{string.Join(",", p.Select(x => x.Value))}");
                };
                client.Aop.OnExecutingChangeSql = (s, p) =>
                {
                    Console.WriteLine($"OnLogExecuted:输出Sql语句;{s} || 参数为{string.Join(",", p.Select(x => x.Value))}");
                    return new KeyValuePair<string, SugarParameter[]>(s, p);
                };
                client.Aop.OnError = e =>
                {
                    Console.WriteLine($"OnError:Sql语句执行异常:{e.Message}");
                };
                #endregion

                #region SqlSguar过滤器配置查询条件(假删除)
                client.QueryFilter.AddTableFilter<Menus>(m => m.IsDeleted != true);
                #endregion


                #region IUnitOfWorK

                #endregion

                return client;
            });
        }
    }
}
